package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2025-01-12
 * Time:23:49
 */
//线程安全
public class Demo5 {
    //定义一个int类型的变量
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Object locker=new Object();
        Object locker2=new Object();
        Thread t1 = new Thread(() -> {
            //对count进行自增5w次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker) {
                    count++;
                }
            }
        });
        Thread t2 = new Thread(() -> {
        //对count进行自增5w次
            for (int i = 0; i < 50000; i++) {
                synchronized (locker2){
                    count++;
                }
            }
       });
        t1.start();
        //如果没有join不行，因为线程还没有自增完就开始打印了，很可能打印出来的是个0
        t1.join();
        t2.start();
        t2.join();
        //预期结果为10w.
        System.out.println("count:"+count);
    }
}
